use std::fmt::format;
use std::fs::{DirBuilder, File};
use std::io::{ErrorKind, Write};
use std::path::Path;
use std::time::Duration;
use rocket::figment::Figment;
use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors};
use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr};
use std::string::String;
use tracing::error;
use crate::工具包::mysql::get_db;
use crate::工具包::self_config::SelfConfig;


///启动前配置
pub async fn start_config() -> (Figment,Cors) {
	start_config_check_selfconfig();//检查SelfConfig.toml配置文件
	start_config_seaorm_debug_print();//控制日志开放
	start_config_path();//生成基础path
	let rocket = start_config_rocket();//配置Rocket
	let rocket_cors = start_config_rocket_cors();//配置Rocket_Cors 跨域
	let db = start_config_init_mysql_database();//初始化MySql数据库
	
	(rocket,rocket_cors)
}
///检查SelfConfig.toml配置文件
fn start_config_check_selfconfig(){
	//检查SelfConfig.toml配置文件,没有文件就生成文件并且发出panic!()
	if let Err(v) = File::open("./SelfConfig.toml") {
		let mut err_information = String::new();
		match v.kind() {
			ErrorKind::NotFound => {
				err_information.push_str("不存在文件!我已经为您创建~快说谢谢生生~");
				match File::create("./SelfConfig.toml"){
					Ok(mut file) => {
						file.write(r#"
							配置还没完善,目前无法确认字符串...
						"#.as_bytes());
					},
					Err(e) => {
						err_information.push_str(
							&*format!("\n{}\n{}"
							          , "\n我尼码~,创建失败了!我把异常信息给你,你自己找吧"
							          , e.kind()));
					}
				}
			},
			ErrorKind::PermissionDenied =>{
				err_information.push_str("没有权限.建议使用root用户启动 或者 修改文件权限");
			}
			_ => {
				err_information.push_str("勇者!你遇到了传说级异常!作者懒得处理,你只能靠你自己处理它!");
			}
		}
		println!("[Err](From : SelfConfig.toml):{}",err_information);
		panic!("死咯~");
	}
}
///生成基础path
fn start_config_path(){
	let config = SelfConfig::get_self_config();
	let a = &config.path;
	let path = Path::new(&a.root);
	DirBuilder::new().create(path);//主目录
	DirBuilder::new().create(path.join(&a.cent_piece));//分片目录
	DirBuilder::new().create(path.join(&a.tem));//临时目录
}
///配置Rocket
fn start_config_rocket() -> Figment{
	let config = SelfConfig::get_self_config();
	rocket::Config::figment()
		.merge(("port",&config.rocket.port))
		.merge(("address",&config.rocket.address))
		.merge(("temp_dir", format!("{}/{}",&config.path.root,&config.path.tem)))
		.merge(("limits.file","100MB"))
}
///配置Rocket_Cors 跨域
fn start_config_rocket_cors()-> Cors {
	rocket_cors::CorsOptions {
		allowed_origins:AllowedOrigins::All,
		allowed_headers: AllowedHeaders::All,
		allow_credentials: true,
		..Default::default()
	}.to_cors().expect("Rocket_Cors配置存在问题")
}

//----------以下是已完成函数----------//

///控制日志开放
fn start_config_seaorm_debug_print(){
	let config = SelfConfig::get_self_config().log;
	if !config { return; }
	//我不懂这玩意,若需要,在学习
	tracing_subscriber::fmt()
		.with_max_level(tracing::Level::DEBUG)
		.with_test_writer()
		.init();
}
///初始化MySql数据库
fn start_config_init_mysql_database() -> &'static DatabaseConnection{
	get_db()
}